﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace RegexLib.Web.Models.Web
{
	public class RxTester
	{
		public static List<RxMatch> GetMatches(Regex regex, string source)
		{
			MatchCollection matches = regex.Matches(source);
			List<RxMatch> ms = new List<RxMatch>();

			for (int i = 0; i < matches.Count; i++)
			{
				Match m = matches[i];
				RxMatch rm = new RxMatch()
				{
					Index = m.Index,
					Length = m.Length,
					Value = HttpUtility.HtmlEncode(m.Value),
					Groups = new List<RxGroup>()
				};
				ms.Add(rm);

				for (int j = 0; j < m.Groups.Count; j++)
				{
					Group g = m.Groups[j];
					RxGroup rg = new RxGroup()
					{
						Name = HttpUtility.HtmlEncode(regex.GroupNameFromNumber(j)),
						Index = g.Index,
						Length = g.Length,
						Value = HttpUtility.HtmlEncode(g.Value),
						Captures = new List<RxCapture>()
					};
					rm.Groups.Add(rg);

					for (int k = 0; k < g.Captures.Count; k++)
					{
						Capture c = g.Captures[k];
						RxCapture rc = new RxCapture()
						{
							Index = c.Index,
							Length = c.Length,
							Value = HttpUtility.HtmlEncode(c.Value)
						};
						rg.Captures.Add(rc);
					}
				}
			}

			return ms;
		}

		public class RxMatch
		{
			public int Index { get; set; }
			public int Length { get; set; }
			public string Value { get; set; }

			public List<RxGroup> Groups { get; set; }

			public RxMatch()
			{
				this.Groups = new List<RxGroup>();
			}
		}

		public class RxGroup
		{
			public string Name { get; set; }
			public int Index { get; set; }
			public int Length { get; set; }
			public string Value { get; set; }

			public List<RxCapture> Captures { get; set; }

			public RxGroup()
			{
				this.Captures = new List<RxCapture>();
			}
		}

		public class RxCapture
		{
			public int Index { get; set; }
			public int Length { get; set; }
			public string Value { get; set; }
		}
	}
}
